﻿using KingerRobot.PCRBW.Dao;
using KingerRobot.PCRMES.Dao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace KingerRobot.PCRBW.SpiService;

public class MesProductLockImpl: IMesProductLockService
{
    IMesLockRepositories _mesLockRepositories=new MesLockRepositories();
    IRcsLocationRepositories _rcsLocationRepositories = new RcsLocationRepositories();

    public int SnycMesLock(MesLock mesLock)
    {
        Expression<Func<MesLock, bool>> whereExpression = x => true;
        whereExpression = whereExpression.And(d => d.LockId == mesLock.LockId);
       var locks= _mesLockRepositories.First(whereExpression);
        if (locks == null)
        {
            return _mesLockRepositories.Add(mesLock);
        }
        else
        {
            return _mesLockRepositories.Update(whereExpression,mesLock);
        }
         
    }


    public void UpdateLoctionLock()
    {
        Expression<Func<PORcsLocation, bool>> whereExpression = x => true;
        whereExpression = whereExpression.And(d => d.LocType ==3);

        var rcsLocationList=_rcsLocationRepositories.Query(whereExpression);
        var result = _mesLockRepositories.Query();
        if (result == null || result.Count == 0) return;

        foreach (var item in rcsLocationList)
        {
            var _mesLock= result.FirstOrDefault(d=>d.PartNumber == item.MaterialId);
            if (_mesLock == null) continue;
            PORcsLocation pORcsLocation = new PORcsLocation();
            pORcsLocation.Id= item.Id;
            pORcsLocation.OutLock = Convert.ToInt32(_mesLock.PassFlag);

            Expression<Func<PORcsLocation, bool>> whereLocExpression = x => true;
            whereLocExpression = whereLocExpression.And(d => d.Id == item.Id);
            _rcsLocationRepositories.Update(whereLocExpression, pORcsLocation);
        }
    }
}
